﻿# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.favoriteCartDao import FavoriteCartDao
from com.zzh.dao_v2.AuthTokenOperation import authTokenOperation

from . import app

CORS(app, supports_credentials=True)


@app.route('/insertFavorCart', methods=['POST'])
def insert_favor_cart():
    """
    添加信息
    :return:
    """
    if not request.json:
        abort(400)
    info = {
        'userId': request.json.get('userId', ''),
        'itemId': request.json.get('itemId', ''),
        'isLock': request.json.get('isLock', 0)
    }

    info = FavoriteCartDao().insertFavoriteCart(info)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findFavorCartById', methods=['POST'])
def find_favor_cart_by_id():
    """
    根据ID查询
    :return:
    """
    if not request.json:
        abort(400)
    favorId = request.json.get('favorId', '')
    info = FavoriteCartDao().findFavorById(favorId)

    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/findFavorCartByCondition', methods=['POST'])
def find_favor_cart_by_condition():
    """
    条件查询
    :return:
    """

    if not request.json:
        abort(400)
    try:
        token = request.headers.get('Access-Token')
    except:
        return jsonify({"message": {"code": 0, "info": "需要参数   Access-Token"}})

    checkResult = authTokenOperation().veryfyToken(token)
    if checkResult:

        try:
            page = request.json['page']
            pageIndex = page["pageIndex"]
            pageSize = page["pageSize"]
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})

        try:
            conditions = request.json['condition']
        except:
            return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
        try:
            multiSort = request.json['multiSort']
        except:
            return jsonify({"message": "未传入排序规则multiSort"})

        info, total = FavoriteCartDao().findFavorByCondition(pageIndex=pageIndex, pageSize=pageSize,
                                                             conditions=conditions,
                                                             multiSort=multiSort)

        if info:
            return jsonify({"total": total, "info": info, "message": {"code": 1, "status": "success"}})
        else:
            return jsonify({"info": [], "message": {"code": 0, "status": "No such data"}})
    else:
        loginUrl = "http://121.40.183.170:5005/zzh/app/v2/userLogin"
        return jsonify({"message": "token验证失败，请重新前往登录界面验证用户名和密码", "userLoginUrl": loginUrl})


@app.route('/deleteFavorCartByIds', methods=['POST'])
def delete_favor_cart_by_ids():
    """
    根据ID删除，ID以数组形式传递
    :return:
    """
    if not request.json:
        abort(400)
    idArray = request.json.get('idArray', [0])

    info = FavoriteCartDao().deleteFavort(idArray)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/updateFavorCartById', methods=['POST'])
def update_favor_cart_by_id():
    """
    更新
    :return:
    """
    if not request.json:
        abort(400)
    try:
        id = request.json['id']
    except:
        return jsonify({"message": {"code": 0, "status": "请传入修改信息的ID"}})
    oldInfo = FavoriteCartDao().selectFavor(id)
    info = {
        'id': request.json['id'],
        'userId': request.json.get('userId', oldInfo[1]),
        'itemId': request.json.get('itemId', oldInfo[2]),
        'isLock': request.json.get('isLock', oldInfo[3])
    }

    info = FavoriteCartDao().updateFavor(info)
    if info:
        return jsonify({"info": info, "message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/addFavoriteCarts', methods=['POST'])
def addFavoriteCarts():
    """
    批量添加收藏车
    :return:
    """
    if not request.json:
        abort(400)
    try:
        data = {
            "userId": request.json['userId'],
            "itemId": request.json['itemId'],
            "isLock": request.json['isLock']
        }
    except:
        return jsonify({"message": {"code": 0, "status": "lack required arguments"}})
    # check arguments type
    if not isinstance(data['userId'], int) and not isinstance(data['isLock'], int):
        return jsonify({"message": {"code": 0, "status": "type error.(userId or isLock)"}})
    for elem in data['itemId']:
        if not isinstance(elem, int):
            return jsonify({"message": {"code": 0, "status": "type error.(itemId)"}})

    rs = FavoriteCartDao().addFavoriteCart(data)
    if rs:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})


@app.route('/removeFavoriteCarts', methods=['POST'])
def removeFavoriteCarts():
    """
    批量删除收藏车
    :return:
    """
    if not request.json:
        abort(400)
    try:
        data = {
            "userId": request.json['userId'],
            "itemId": request.json['itemId'],
            "isLock": request.json['isLock']
        }
    except:
        return jsonify({"message": {"code": 0, "status": "缺少必要参数"}})

    info = FavoriteCartDao().removeFavorCart(data)
    if info:
        return jsonify({"message": {"code": 1, "status": "success"}})
    else:
        return jsonify({"message": {"code": 0, "status": "error"}})